package com.thams.service;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;

import com.thams.dao.i.ICustomerDao;
import com.thams.dao.i.IInventoryClassDao;
import com.thams.dao.i.IInventoryDao;
import com.thams.dao.i.ISalesOrderDao;
import com.thams.dao.i.IUserDefineDao;
import com.thams.entity.BasPart;
import com.thams.entity.ComputationUnit;
import com.thams.entity.Customer;
import com.thams.entity.Inventory;
import com.thams.entity.InventoryClass;
import com.thams.entity.InventorySub;
import com.thams.entity.SoSodetails;
import com.thams.entity.SoSomain;
import com.thams.entity.UserDefine;
import com.thams.service.i.IU8Service;

public class U8Service extends DataBaseService implements IU8Service {

	@Autowired
	private IInventoryClassDao inventoryClassDao;
	@Autowired
	private IInventoryDao inventoryDao;
	@Autowired
	private IUserDefineDao userDefineDao;
	@Autowired
	private ICustomerDao customerDao;
	@Autowired
	private ISalesOrderDao salesOrderDao;
	@Autowired
	private DataSource systemDataSource;

	@Override
	public String getInventoryClassListJsonForJquery() {
		List<InventoryClass> inventoryClassList = inventoryClassDao.getInventoryClassList();
		List<InventoryClass> fenleiList = new ArrayList<InventoryClass>();
		for (InventoryClass inventoryClass : inventoryClassList) {
			if (inventoryClass.getCinvCcode() != null
					&& inventoryClass.getCinvCcode().length() == 2) {// 第一级菜单
				fenleiList.add(generatorClassChildList(inventoryClassList,
						inventoryClass));
			}
		}

		// StringBuilder sb = new StringBuilder("{\"result\":[");
		StringBuilder sb = new StringBuilder(
				"[{\"id\":\"0\",\"name\":\"0-分类\",\"children\":[");
		for (int i = 0; i < fenleiList.size(); i++) {
			InventoryClass inventoryClass = fenleiList.get(i);
			sb.append(inventoryClass.toJSONForJQuery());
			if (i != fenleiList.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]}]");
		return sb.toString();
	}

	
	@Override
	public String getInventoryClassListJson() {
		List<InventoryClass> inventoryClassList = inventoryClassDao.getInventoryClassList();
		List<InventoryClass> fenleiList = new ArrayList<InventoryClass>();
		for (InventoryClass inventoryClass : inventoryClassList) {
			if (inventoryClass.getCinvCcode() != null
					&& inventoryClass.getCinvCcode().length() == 2) {// 第一级菜单
				fenleiList.add(generatorClassChildList(inventoryClassList,
						inventoryClass));
			}
		}

		// StringBuilder sb = new StringBuilder("{\"result\":[");
		StringBuilder sb = new StringBuilder(
				"{\"property\":{\"id\":\"0\",\"name\":\"0-分类\"},\"children\":[");
		for (int i = 0; i < fenleiList.size(); i++) {
			InventoryClass inventoryClass = fenleiList.get(i);
			sb.append(inventoryClass.toJSON());
			if (i != fenleiList.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]}");
		return sb.toString();
	}
	
	private InventoryClass generatorClassChildList(List<InventoryClass> ls,
			InventoryClass inv) {
		for (InventoryClass invclass : ls) {
			int tempL = invclass.getCinvCcode().replaceFirst(
					inv.getCinvCcode(), "").length();
			boolean isSon = tempL > 1 && tempL < 4;
			boolean startWith = invclass.getCinvCcode().startsWith(
					inv.getCinvCcode());
			if (!inv.getCinvCcode().equals(invclass.getCinvCcode())
					&& startWith && isSon) { // 如果是子节点
				// 判断是否包含子节点
				if (null != inv && null == inv.getChildren()) {
					inv.setChildren(new ArrayList<InventoryClass>());
				}
				invclass = generatorClassChildList(ls, invclass);
				inv.getChildren().add(invclass);
			}
		}
		return inv;
	}

	@Override
	public void insertInventory(Inventory inventory,InventorySub inventorySub,BasPart basPart){
		inventorySub.setCinvSubCode(inventory.getCinvCode());
		basPart.setInvCode(inventory.getCinvCode());
		basPart.setPartId(getMaxFieldByTableName("bas_part", "PartId")+1);
		inventoryDao.insertInventory(inventory);//存货
		inventoryDao.insertInventorySub(inventorySub);//存货附表1
		inventoryDao.insertBasPart(basPart);//存货附表2
	}

	@Override
	public void insertInventoryClass(InventoryClass inventoryClass){
		if(inventoryClass.getCinvCcode()==null){
			throw new RuntimeException("编号不能为空");
		}
		try {
			Integer.parseInt(inventoryClass.getCinvCcode());
		} catch (Exception e) {
			throw new RuntimeException("编号格式不对");
		}
		if(inventoryClass.getParentCinvCcode()==null||inventoryClass.getParentCinvCcode().equals("0")){//选择的是根节点 0
			if(inventoryClass.getIinvCgrade()!=1){
				throw new RuntimeException("编号级别应该为1");
			}
			inventoryClassDao.insertInventoryClass(inventoryClass);
			return;
		}
		if(inventoryClass.getIinvCgrade()==null||(inventoryClass.getIinvCgrade().intValue()*3-1)!=(inventoryClass.getParentCinvCcode()+inventoryClass.getCinvCcode()).length()){
			throw new RuntimeException("编号和级别不对应");
		}
		if(inventoryClass.getCinvCcode()==null||inventoryClass.getCinvCcode().length()!=3){
			throw new RuntimeException("分类编号不符合规则");
		}
		if(inventoryClass.getIinvCgrade()>3){
			throw new RuntimeException("分类编号最多到第三级");
		}
		inventoryClass.setCinvCcode(inventoryClass.getParentCinvCcode()+inventoryClass.getCinvCcode());
		inventoryClassDao.insertInventoryClass(inventoryClass);
		executeSQL("update INVENTORYCLASS set bInvCEnd = 0 where cInvCCode = '"+inventoryClass.getParentCinvCcode()+"'");
	}

	@Override
	public List<UserDefine> getUserDefineList() {
		return userDefineDao.getUserDefineList();
	}

	@Override
	public List<Customer> getCustomerList() {
		return customerDao.getCustomerList();
	}

	@Override
	public void insertSoSodetails(SoSodetails soSodetails) {
		soSodetails.setIsosId(getMaxFieldByTableName("SO_SODetails", "iSOsID")+1);
		salesOrderDao.insertSoSodetails(soSodetails);
		updateUFSystemUACount("update UA_Identity set iChildId = iChildId+1 where cVouchType='Somain' and cAcc_Id = '999'");
	}

	@Override
	public String insertSoSomain(SoSomain soSoMain) {
//		String tempCsocode = (String) executeQuerySQL("select Max(cSOCode) from SO_SOMain");
//		if(tempCsocode==null||tempCsocode.equals("")){
//			tempCsocode = "0";
//		}
//		String s = returnAddedZero(Integer.parseInt(tempCsocode)+1, 10);
		String s = soSoMain.getCsocode();
//		soSoMain.setCsocode(s);
		soSoMain.setId(getMaxFieldByTableName("SO_SOMain", "ID")+1);
		salesOrderDao.insertSoSomain(soSoMain);
		s += "," + soSoMain.getId();
		updateUFSystemUACount("update UA_Identity set iFatherId = iFatherId+1 where cVouchType='Somain' and cAcc_Id = '999'");
		return s;
	}
	
	private void updateUFSystemUACount(String sql){
		Connection conn = null;
		Statement stmt = null;
		try {
			conn= systemDataSource.getConnection();
			stmt = conn.createStatement();
			stmt.execute(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				stmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}	
	/**
	 * 补零操作
	 * @param num 要补零的整数
	 * @param length 位数
	 * @return str
	 */
	private String returnAddedZero(int num,int length){
		if(length==0){
			return String.valueOf(num);
		}
		//得到一个NumberFormat的实例
        NumberFormat nf = NumberFormat.getInstance();
        //设置是否使用分组
        nf.setGroupingUsed(false);
        //设置最大整数位数
        nf.setMaximumIntegerDigits(length);
        //设置最小整数位数    
        nf.setMinimumIntegerDigits(length);
        //输出测试语句
        return nf.format(num);
	}

	@Override
	public String getInventoryNumber(String cinvCode) {
		String result = null;
		try {
			BigDecimal d = (BigDecimal) executeQuerySQL("select sum(iQuantity) from CurrentStock where cInvCode = '"+cinvCode+"'");
			String danwei = (String) executeQuerySQL("select cComUnitName from ComputationUnit where cComunitCode = (select cComUnitCode from Inventory where cInvCode = '"+cinvCode+"')");
			if(danwei!=null&&d!=null){
				result = String.valueOf(d.intValue())+"("+danwei+")";
			}
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		return result; // 未完
	}

	@Override
	public List<ComputationUnit> getComputationUnitList() {
		try {
			return inventoryDao.getComputationUnitList();
		} catch (DataAccessException e) {
			e.printStackTrace();
			return null;
		}
	}

	

	
	
}
